package com.jacobson.core.utils

import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.jacobson.core.base.FragmentImmersive
import com.jacobson.core.base.Immersive
import com.jacobson.core.utils.AppUtils.checkDeviceHasNavigationBar
import com.jacobson.core.utils.AppUtils.getStatusBarHeight
import com.jacobson.core.widget.logger.LoggerFactory

/**
 * ================================================
 * 沉浸式帮助类
 * @author Wucz on 2018/7/17 13:54
 * ================================================
 */

object ImmersiveExtensions {
    fun immersive(activity: Activity) {
        activity.run {
            javaClass.getAnnotation(Immersive::class.java)?.let { it ->
                immersive(this, it)
            }
        }
    }

    fun immersive(fragment: Fragment): Boolean {
        var result = false
        fragment.run {
            javaClass.getAnnotation(FragmentImmersive::class.java)?.let { it ->
                //设置状态栏字体颜色
                activity?.run {
                    result = if (it.isLightMode) {
                        AppUtils.setStatusBarLightMode(this)
                    } else {
                        AppUtils.setStatusBarDarkMode(this)
                    }
                }
            }
        }
        LoggerFactory.getLogger().w("Immersive >>>  ${fragment.javaClass.simpleName}")
        return result
    }

    fun immersive(activity: Activity?, immersive: Immersive) {
        activity?.run {
            //无标题栏
            if (immersive.featureNoTitle) {
                if (this is AppCompatActivity) {
                    //如果正在显示则关闭显示
                    supportActionBar?.takeIf { it.isShowing }?.hide()
                } else {
                    requestWindowFeature(Window.FEATURE_NO_TITLE)
                }
            }
            //全屏模式
            if (immersive.fullScreen) {
                window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
            }
            //透明状态栏
            if (immersive.supportWindowTranslucentStatus) {
                translucentStatus(this)
            }
            //设置状态栏字体颜色
            if (immersive.isLightMode) {
                AppUtils.setStatusBarLightMode(this)
            } else {
                AppUtils.setStatusBarDarkMode(this)
            }
        }
    }

    fun fitsSystemWindows(fragment: Fragment) {
        LoggerFactory.getLogger().i("Immersive#fitsSystemWindows >>>  ${fragment.javaClass.simpleName}")
        fragment.view?.run {
            dispatchFitsSystemWindows(this)
        }
    }

    /** 增加View的paddingTop,增加的值为状态栏高度 (智能判断，并设置高度) */
    fun setPaddingSmart(context: Context?, view: View) {
        if (Build.VERSION.SDK_INT >= MIN_API) {
            val lp = view.layoutParams
            if (lp != null && lp.height > 0) {
                lp.height += getStatusBarHeight(context ?: view.context)//增高
            }
            view.setPadding(view.paddingLeft,
                    view.paddingTop + getStatusBarHeight(context ?: view.context),
                    view.paddingRight,
                    view.paddingBottom)
        }
    }

    private fun dispatchFitsSystemWindows(view: View?): Boolean {
        view?.run {
            if (fitsSystemWindows) {
                LoggerFactory.getLogger().d("Immersive#dispatchFitsSystemWindows->$this fits OldPadding[$paddingStart, $paddingTop, $paddingEnd, $paddingBottom]")
                setPaddingSmart(context, this)
                parent?.requestLayout()
                requestLayout()
                postInvalidate()
                LoggerFactory.getLogger().d("Immersive#dispatchFitsSystemWindows->$this fits newPadding[$paddingStart, $paddingTop, $paddingEnd, $paddingBottom]")
                return true
            }
            if (this is ViewGroup) {
                for (position in 0 until childCount) {
                    if (dispatchFitsSystemWindows(getChildAt(position))) {
                        return true
                    }
                }
            }
        }
        return false
    }

    fun fitsSystemWindows(activity: Activity) {
        activity.run {
            javaClass.getAnnotation(Immersive::class.java)?.let {
                //设置fitsSystemWindow属性
                if (it.fitSystemWindows) {
                    findViewById<ViewGroup>(Window.ID_ANDROID_CONTENT)?.getChildAt(0)?.fitsSystemWindows = true
                }
            }
        }
    }

    @TargetApi(19)
    private fun translucentStatus(activity: Activity) {
        activity.run {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS.or(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION))
                window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN.or(View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                window.statusBarColor = Color.TRANSPARENT
                window.navigationBarColor = Color.TRANSPARENT
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                        WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            }
        }
    }

    fun fitNavigationBar(activity: Activity) {
        activity.run {
            javaClass.getAnnotation(Immersive::class.java)?.let {
                //设置fitsSystemWindow属性
                if (it.fitNavigationBar && checkDeviceHasNavigationBar(activity)) {
                    AndroidBug5497Workaround.assistActivity(activity)
//                    findViewById<ViewGroup>(Window.ID_ANDROID_CONTENT)?.getChildAt(0)?.fitsSystemWindows = true
                }
            }
        }
    }

    fun supportAndroidBug5497Workaround(activity: Activity) {
        activity.run {
            javaClass.getAnnotation(Immersive::class.java)?.takeIf { it.supportAndroidBug5497 }?.let {
                AndroidBug5497Workaround.assistActivity(activity)
            }
        }

    }

    private const val MIN_API = 19
}